import type { IProduct, IChapter, IComment, IEpisode } from '@/typings/interface';
import { getDetail, getChapterList, getCommentPage, getMeterial } from '@/api/video';
import navigateTo from '@/utils/navigator';
import type { IPage } from '@/typings/api';
import { isFreeEpisode } from '@/utils';

export const useVideo = defineStore('video', () => {
  // 课程信息
  let videoInfo = ref<any | IProduct>();

  // 课程章集
  let videoChapterList = ref<IChapter[]>([]);
  let currentEpisodeId = ref<number>(-1);
  let commentPage = ref<IPage<IComment>>();

  const { isLogin } = storeToRefs(useUser());
  // 集标题
  const currentEpisodeTitle = computed(() => {
    return (
      videoChapterList.value
        .flatMap((c: any) => c.episodeList)
        .filter((e: any) => e.id === currentEpisodeId.value)[0]?.title ??
      '出现错误，找不到标题'
    );
  });

  // 获取视频信息
  async function init(videoId: number) {
    const { data: _videoInfo } = await getDetail(videoId);
    videoInfo.value = _videoInfo;

    // 获取章集
    const { data: _videoChapterList } = await getChapterList(videoId);
    videoChapterList.value = _videoChapterList;

    // 获取评论
    const { data: _commentPage } = await getCommentPage({
      page: 1,
      size: 10,
      id: videoId,
    });
    commentPage.value = _commentPage;
    // 课程资料获取
    if (isLogin.value) {
      const { data: _meterial } = await getMeterial(videoId);
      videoInfo.value = {
        ...videoInfo.value,
        note_url: _meterial?.note_url,
        bd_zip_url: _meterial?.bd_zip_url,
        ali_zip_url: _meterial?.ali_zip_url,
      };
    }
  }

  // 跳转详情页
  async function toDetail(videoId: number) {
    navigateTo(`/pages/detail/index?id=${videoId}`);
    await init(videoId);
  }

  // 切换集
  function changeEpisodeId(eid: number) {
    currentEpisodeId.value = eid;
  }

  // 跳转播放页面方法
  async function toPlayer(
    episode: Pick<IEpisode, 'free' | 'id'>,
    productId?: number
  ) {
    if (
      await isFreeEpisode({
        free: episode.free,
        product_id: productId ?? videoInfo.value?.id ?? 1,
      })
    ) {
      currentEpisodeId.value = episode.id;
      navigateTo(
        `/pages/player/index?id=${productId ?? videoInfo.value?.id}&eid=${episode.id
        }`,
        { isNeedLogin: true }
      );
    }
  }

  // 自动播放切换集+集是否可观看
  async function nextEpisode() {
    let _episode: IEpisode | undefined;
    let needNextEpisode = false; // 判断该集是否为某章的最后一集
    // 不存在集id时停止
    if (currentEpisodeId.value === -1) return false;

    try {
      videoChapterList.value.forEach((chapter, index) => {
        // 章无更多集则自动跳转下一章播放
        if (needNextEpisode) {
          _episode = videoChapterList.value[index].episodeList[0];
          // 成功跳转下一章则停止循环
          throw new Error('We got episode.');
        }

        chapter.episodeList.forEach((episode, idx) => {
          if (episode.id === currentEpisodeId.value) {
            // 判断是不是该章的最后一集，如果不是则自动切换
            if (idx + 1 < chapter.episodeList.length)
              _episode = chapter.episodeList[idx + 1];
            else needNextEpisode = true;
          }
        });
      });
    } catch (ignore) { }

    // 播放最后一集则结束
    if (!_episode) return false;

    // 判断该集是否免费
    if (!(await isFreeEpisode(_episode))) return false;

    // 更改pinia里的集id
    currentEpisodeId.value = _episode.id;
    return true;
  }

  return ({
    videoInfo,
    init,
    toDetail,
    videoChapterList,
    currentEpisodeId,
    currentEpisodeTitle,
    changeEpisodeId,
    commentPage,
    toPlayer,
    nextEpisode,
  });
});

